package com.leetcode.array;

/**
 * 1.找到最小值的下标 i
 * 2.判断target如果小于nums[0]，在[i , length -1]中查找
 * 3. target > nums[0] ,在[0 , i-1]中查找
 */
public class Leetcode33 {
    // 找到旋转点的小标
    private int findMinIndex(int[] nums) {
        int left = 0;
        int right = nums.length -1;

        // 没有旋转
        if (nums[left] < nums[right]) {
            return 0;
        }

        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > nums[mid + 1]) {
                return mid+1;
            }
            else if (nums[mid] < nums[left]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return 0;
    }

    private int binarySearch(int left, int right, int[] nums, int target) {
        if (nums.length == 1) {
            return nums[0] == target ? 0:-1;
        }

        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == nums[mid]) {
                return mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else if (target < nums[mid]) {
                right = mid - 1;
            }
        }
        return -1;
    }



    public int search(int[] nums, int target) {
        if (nums.length == 0)
            return -1;

        if (nums.length == 1) {
            return target == nums[0]?0:-1;
        }

        int indexRotation = findMinIndex(nums);
        if (indexRotation == 0) {
            return binarySearch(0, nums.length-1, nums, target);
        }

        if (target < nums[0]) {
            return binarySearch(indexRotation, nums.length-1, nums, target);
        } else {
            return binarySearch(0, indexRotation - 1, nums, target);
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[0];
        Leetcode33 leet = new Leetcode33();
        int n = leet.search(arr, 3);
        System.out.println(n);
    }

}
